/** @method useDataSourceData
 *  @description 获取数据源分类
 *  @return Array
 */
import { useEffect, useState } from 'react';
import { DATA_SOURCE_STATUS } from 'src/utils/constant';
import services from '../services/api';
import dataSourceVariable from '../utils/dataSource';

export default function useDataSourceData(status = DATA_SOURCE_STATUS._ENABLE) {
  const [dataSourceType, setDataSourceType] = useState(dataSourceVariable.dataSourceType);
  const [varData, setVarData] = useState(dataSourceVariable.varData);

  useEffect(() => {
    if (varData && Object.keys(varData).length === 0) {
      getDataSourceType();
    }
  }, []);

  const getDataSourceType = async () => {
    try {
      const res = await services.dataSourceMng.type({ status });
      if (res.code === '0') {
        const resList = await Promise.all(
          res.data.map((item) =>
            services.dataSourceMng.typeList({
              dataSourceCode: item.code,
            })
          )
        );
        const varData = {};
        const dataSourceType = {};
        res.data.forEach(({ code, name, type }, index) => {
          dataSourceType[code] = {
            label: name,
            key: code,
            name: type,
          };
          varData[code] = resList[index].code === '0' ? resList[index].data : [];
        });
        // console.log('resList: ', resList);
        // console.log('varData: ', varData);
        // console.log('dataSourceType: ', dataSourceType);
        dataSourceVariable.dataSourceType = dataSourceType;
        dataSourceVariable.varData = varData;
        setDataSourceType(dataSourceType);
        setVarData(varData);
      }
    } catch (error) {
      console.error(error);
    }
  };

  return {
    dataSourceType,
    varData,
  };
}
